home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 117 / PC Guia 117.iso / Software / Produtividade / Software2 / Product4 / Setup.exe / drupal-4.6.0 / modules / poll.module < prev    next >
Encoding:
Text File  |  2005-04-01  |  14.3 KB  |  459 lines

  1. <?php
  2. // $Id: poll.module,v 1.162 2005/04/01 15:55:00 dries Exp $
  3.  
  4. /**
  5.  * @file
  6.  * Enables your site to capture votes on different topics in the form of multiple
  7.  * choice questions.
  8.  */
  9.  
  10. /**
  11.  * Implementation of hook_help().
  12.  */
  13. function poll_help($section) {
  14.   switch ($section) {
  15.     case 'admin/help#poll':
  16.       return t("
  17.       <p>Users with the correct <a href=\"%permissions\">permissions</a> can create and/or vote on polls.</p>
  18.       <ul>
  19.       <li>To create a poll a user needs the \"create polls\" permission.</li>
  20.       <li>To vote on a poll question a user must have the \"vote on polls\" permission.</li>
  21.       <li>To view the results one needs the \"access content\" permission.</li>
  22.       <li>To administer polls you need the \"administer nodes\" permission.</li>
  23.       </ul>
  24.       <p>Creating a poll is much like creating any other node. Click \"create poll\" in your user box. The title of the poll should be the question, then enter the answers and the \"base\" vote counts. You can also choose the time period over which the vote will run.</p><p>The <a href=\"%poll\">Poll</a> item in the navigation links will take you to a page where you can see all the current polls, vote on them (if you haven't already) and view the results.</p>", array("%permissions" => url("admin/access/permissions"), "%poll" => url("poll")));
  25.     case 'admin/modules#description':
  26.       return t("Allows your site to capture votes on different topics in the form of multiple choice questions.");
  27.     case 'node/add#poll':
  28.       return t("A poll is a multiple-choice question which visitors can vote on.");
  29.   }
  30. }
  31.  
  32. /**
  33.  * Implementation of hook_access().
  34.  */
  35. function poll_access($op, $node) {
  36.   if ($op == 'create') {
  37.     return user_access('create polls');
  38.   }
  39. }
  40.  
  41. /**
  42.  * Implementation of hook_block().
  43.  *
  44.  * Generates a block containing the latest poll.
  45.  */
  46. function poll_block($op = 'list', $delta = 0) {
  47.   if (user_access('access content')) {
  48.     if ($op == 'list') {
  49.       $blocks[0]['info'] = t('Most recent poll');
  50.       return $blocks;
  51.     }
  52.     else if ($op == 'view') {
  53.       // Retrieve the latest poll.
  54.       $sql = db_rewrite_sql("SELECT MAX(n.created) FROM {node} n INNER JOIN {poll} p ON p.nid = n.nid WHERE n.status = 1 AND p.active = 1 AND n.moderate = 0");
  55.       $timestamp = db_result(db_query($sql));
  56.       if ($timestamp) {
  57.         $poll = node_load(array('type' => 'poll', 'created' => $timestamp, 'moderate' => 0, 'status' => 1));
  58.  
  59.         if ($poll->nid) {
  60.           // poll_view() dumps the output into $poll->body.
  61.           poll_view($poll, 1, 0, 1);
  62.         }
  63.       }
  64.       $block['subject'] = t('Poll');
  65.       $block['content'] = $poll->body;
  66.       return $block;
  67.     }
  68.   }
  69. }
  70.  
  71. /**
  72.  * Implementation of hook_cron().
  73.  *
  74.  * Closes polls that have exceeded their allowed runtime.
  75.  */
  76. function poll_cron() {
  77.   $result = db_query('SELECT p.nid FROM {poll} p INNER JOIN {node} n ON p.nid = n.nid WHERE (n.created + p.runtime) < '. time() .' AND p.active = 1 AND p.runtime != 0');
  78.   while ($poll = db_fetch_object($result)) {
  79.     db_query("UPDATE {poll} SET active = 0 WHERE nid = %d", $poll->nid);
  80.   }
  81. }
  82.  
  83. /**
  84.  * Implementation of hook_delete().
  85.  */
  86. function poll_delete($node) {
  87.   db_query("DELETE FROM {poll} WHERE nid = %d", $node->nid);
  88.   db_query("DELETE FROM {poll_choices} WHERE nid = %d", $node->nid);
  89. }
  90.  
  91. /**
  92.  * Implementation of hook_validate().
  93.  */
  94. function poll_validate(&$node) {
  95.   if (isset($node->title)) {
  96.     // Check for at least two options and validate amount of votes:
  97.     $realchoices = 0;
  98.     foreach ($node->choice as $i => $choice) {
  99.       if ($choice['chtext'] != '') {
  100.         $realchoices++;
  101.       }
  102.  
  103.       if ($choice['chvotes'] < 0) {
  104.         form_set_error("choice][$i][chvotes", t('Negative values are not allowed.'));
  105.       }
  106.     }
  107.  
  108.     if ($realchoices < 2) {
  109.       form_set_error("choice][$realchoices][chtext", t('You must fill in at least two choices.'));
  110.     }
  111.   }
  112.  
  113.   $node->teaser = poll_teaser($node);
  114. }
  115.  
  116. /**
  117.  * Implementation of hook_form().
  118.  */
  119. function poll_form(&$node) {
  120.   $admin = user_access('administer nodes');
  121.  
  122.   if (function_exists('taxonomy_node_form')) {
  123.     $output = implode('', taxonomy_node_form('poll', $node));
  124.   }
  125.  
  126.   if (!isset($node->choices)) {
  127.     $node->choices = max(2, count($node->choice) ? count($node->choice) : 5);
  128.   }
  129.  
  130.   // User ticked 'need more choices'.
  131.   if ($node->morechoices) {
  132.     $node->choices *= 2;
  133.   }
  134.  
  135.   $output .= '<div class="poll-form">';
  136.  
  137.   // Poll choices
  138.   $opts = drupal_map_assoc(range(2, $node->choices * 2 + 5));
  139.   for ($a = 0; $a < $node->choices; $a++) {
  140.     $group1 .= form_textfield(t('Choice %n', array('%n' => ($a + 1))), "choice][$a][chtext", $node->choice[$a]['chtext'], 50, 127);
  141.     if ($admin) {
  142.       $group1 .= form_textfield(t('Votes for choice %n', array('%n' => ($a + 1))), "choice][$a][chvotes", (int)$node->choice[$a]['chvotes'], 7, 7);
  143.     }
  144.   }
  145.   $group1 .= form_hidden('choices', $node->choices);
  146.   $group1 .= form_checkbox(t('Need more choices'), 'morechoices', 1, 0, t("If the amount of boxes above isn't enough, check this box and click the Preview button below to add some more."));
  147.   $output .= form_group(t('Choices'), $group1);
  148.  
  149.  
  150.   // Poll attributes
  151.   $_duration = array(0 => t('Unlimited')) + drupal_map_assoc(array(86400, 172800, 345600, 604800, 1209600, 2419200, 4838400, 9676800, 31536000), "format_interval");
  152.   $_active = array(0 => t('Closed'), 1 => t('Active'));
  153.  
  154.   if ($admin) {
  155.     $group2 .= form_radios(t('Poll status'), 'active', isset($node->active) ? $node->active : 1, $_active, t('When a poll is closed, visitors can no longer vote for it.'));
  156.   }
  157.   $group2 .= form_select(t('Poll duration'), 'runtime', $node->runtime ? $node->runtime : 0, $_duration, t('After this period, the poll will be closed automatically.'));
  158.  
  159.   $output .= form_group(t('Settings'), $group2);
  160.   $output .= '</div>';
  161.  
  162.   return $output;
  163. }
  164.  
  165. function poll_insert($node) {
  166.   if (!user_access('administer nodes')) {
  167.     // Make sure all votes are 0 initially
  168.     foreach ($node->choice as $i => $choice) {
  169.       $node->choice[$i]['chvotes'] = 0;
  170.     }
  171.     $node->active = 1;
  172.   }
  173.  
  174.   db_query("INSERT INTO {poll} (nid, runtime, polled, active) VALUES (%d, %d, '', %d)", $node->nid, $node->runtime, $node->active);
  175.  
  176.   foreach ($node->choice as $choice) {
  177.     if ($choice['chtext'] != '') {
  178.       db_query("INSERT INTO {poll_choices} (nid, chtext, chvotes, chorder) VALUES (%d, '%s', %d, %d)", $node->nid, $choice['chtext'], $choice['chvotes'], $i++);
  179.     }
  180.   }
  181. }
  182.  
  183. /**
  184.  * Implementation of hook_menu().
  185.  */
  186. function poll_menu($may_cache) {
  187.   $items = array();
  188.  
  189.   if ($may_cache) {
  190.     $items[] = array('path' => 'node/add/poll', 'title' => t('poll'),
  191.       'access' => user_access('create polls'));
  192.     $items[] = array('path' => 'poll', 'title' => t('polls'),
  193.       'callback' => 'poll_page',
  194.       'access' => user_access('access content'),
  195.       'type' => MENU_SUGGESTED_ITEM);
  196.  
  197.     $items[] = array('path' => 'poll/vote',
  198.       'title' => t('vote'),
  199.       'callback' => 'poll_vote',
  200.       'access' => user_access('vote on polls'),
  201.       'type' => MENU_CALLBACK);
  202.   }
  203.   else {
  204.     if (arg(0) == 'node' && is_numeric(arg(1))) {
  205.       $node = node_load(array('nid' => arg(1)));
  206.  
  207.       if ($node->type == 'poll' && $node->allowvotes) {
  208.         $items[] = array('path' => 'node/'. arg(1) .'/results',
  209.           'title' => t('results'),
  210.           'callback' => 'poll_results',
  211.           'access' => user_access('access content'),
  212.           'weight' => 3,
  213.           'type' => MENU_LOCAL_TASK);
  214.       }
  215.     }
  216.   }
  217.  
  218.   return $items;
  219. }
  220.  
  221. /**
  222.  * Determine an adjusted user id, to allow for basic tracking of anonymous
  223.  * users (IP-based).
  224.  */
  225. function poll_uid() {
  226.   global $user;
  227.   if ($user->uid) {
  228.      // Pad the UID with underscores to allow a simple strstr() search
  229.     $id = '_'. $user->uid .'_';
  230.   }
  231.   else {
  232.     $id = $_SERVER['REMOTE_ADDR'];
  233.   }
  234.   return $id;
  235. }
  236.  
  237. /**
  238.  * Implementation of hook_load().
  239.  */
  240. function poll_load($node) {
  241.   // Load the appropriate choices into the $node object
  242.   $poll = db_fetch_object(db_query("SELECT runtime, polled, active FROM {poll} WHERE nid = %d", $node->nid));
  243.  
  244.   $result = db_query("SELECT chtext, chvotes, chorder FROM {poll_choices} WHERE nid = %d ORDER BY chorder", $node->nid);
  245.   while ($choice = db_fetch_array($result)) {
  246.     $poll->choice[$choice['chorder']] = $choice;
  247.   }
  248.  
  249.   // Determine whether or not this user is allowed to vote
  250.   $poll->allowvotes = false;
  251.   if (user_access('vote on polls')) {
  252.     if (!strstr($poll->polled, poll_uid())) {
  253.       $poll->allowvotes = $poll->active;
  254.     }
  255.   }
  256.   return $poll;
  257. }
  258.  
  259. /**
  260.  * Implementation of hook_node_name().
  261.  */
  262. function poll_node_name($node) {
  263.   return t("poll");
  264. }
  265.  
  266. function poll_page() {
  267.   // List all polls
  268.   $sql = "SELECT n.nid, n.title, p.active, n.created, SUM(c.chvotes) AS votes FROM {node} n INNER JOIN {poll} p ON n.nid = p.nid INNER JOIN {poll_choices} c ON n.nid = c.nid WHERE n.status = 1 AND n.moderate = 0 GROUP BY n.nid, n.title, p.active, n.created ORDER BY n.created DESC";
  269.   $sql = db_rewrite_sql($sql);
  270.   $result = pager_query($sql, 15);
  271.   $output = '<ul>';
  272.   while ($node = db_fetch_object($result)) {
  273.     $output .= '<li>'. l($node->title, "node/$node->nid") .' - '. format_plural($node->votes, '1 vote', '%count votes') .' - '. ($node->active ? t('open') : t('closed')) .'</li>';
  274.   }
  275.   $output .= '</ul>';
  276.   $output .= theme("pager", NULL, 15);
  277.   print theme('page', $output);
  278. }
  279.  
  280. /**
  281.  * Implementation of hook_perm().
  282.  */
  283. function poll_perm() {
  284.   return array('create polls', 'vote on polls');
  285. }
  286.  
  287. /**
  288.  * Creates a simple teaser that lists all the choices.
  289.  */
  290. function poll_teaser($node) {
  291.   if (is_array($node->choice)) {
  292.     foreach ($node->choice as $k => $choice) {
  293.       $teaser .= '* '. $choice['chtext'] .'\n';
  294.     }
  295.   }
  296.   return $teaser;
  297. }
  298.  
  299. /**
  300.  * Generates the voting form for a poll.
  301.  */
  302. function poll_view_voting(&$node, $teaser, $page, $block) {
  303.   $output = '<div class="poll">';
  304.  
  305.   $form = '<div class="vote-form">';
  306.   $form .= '<div class="choices">';
  307.   if ($node->choice) {
  308.     $list = array();
  309.     foreach ($node->choice as $i => $choice) {
  310.       $list[$i] = check_plain($choice['chtext']);
  311.     }
  312.     $form .= form_radios($page ? '' : check_plain($node->title), 'choice', -1, $list);
  313.   }
  314.   $form .= '</div>';
  315.   $form .= form_hidden('nid', $node->nid);
  316.   $form .= form_submit(t('Vote'), 'vote') .'</div>';
  317.  
  318.   $output .= form($form, 'post', url('poll/vote/'. $node->nid));
  319.   $output .= '</div>';
  320.  
  321.   return $output;
  322. }
  323.  
  324. /**
  325.  * Generates a graphical representation of the results of a poll.
  326.  */
  327. function poll_view_results(&$node, $teaser, $page, $block) {
  328.   // Display the results
  329.  
  330.   // Count the votes and find the maximum
  331.   foreach ($node->choice as $choice) {
  332.     $votestotal += $choice['chvotes'];
  333.     $votesmax = max($votesmax, $choice['chvotes']);
  334.   }
  335.  
  336.   // Output the divs for the text, bars and percentages
  337.   $output .= '<div class="poll">';
  338.   if ($block) {
  339.     $output .= '<div class="title">'. check_plain($node->title) .'</div>';
  340.   }
  341.   foreach ($node->choice as $i => $choice) {
  342.     if ($choice['chtext'] != '') {
  343.       $percentage = round($choice['chvotes'] * 100 / max($votestotal, 1));
  344.       $output .= '<div class="text">'. check_plain($choice['chtext']) .'</div>';
  345.       $output .= '<div class="bar">';
  346.       $output .= '<div style="width: '. $percentage .'%;" class="foreground"></div>';
  347.       $output .= '</div>';
  348.       $output .= '<div class="percent">'. $percentage .'%'. (!$block ? ' ('. format_plural($choice['chvotes'], '1 vote', '%count votes') .')' : '') .'</div>';
  349.     }
  350.   }
  351.   $output .= '<div class="total">'. t('Total votes') .": $votestotal</div>";
  352.  
  353.   $output .= '</div>';
  354.  
  355.   return $output;
  356. }
  357.  
  358. /**
  359.  * Callback for the 'results' tab for polls you can vote on
  360.  */
  361. function poll_results() {
  362.   if ($node = node_load(array('nid' => arg(1)))) {
  363.     drupal_set_title(check_plain($node->title));
  364.     print theme('page', node_show($node, 0));
  365.   }
  366.   else {
  367.     drupal_not_found();
  368.   }
  369. }
  370.  
  371. /**
  372.  * Callback for processing a vote
  373.  */
  374. function poll_vote(&$node) {
  375.   $nid = arg(2);
  376.   if ($node = node_load(array('nid' => $nid))) {
  377.     $edit = $_POST['edit'];
  378.     $choice = $edit['choice'];
  379.     $vote = $_POST['vote'];
  380.  
  381.     if (isset($choice) && isset($node->choice[$choice])) {
  382.       if ($node->allowvotes) {
  383.         $id = poll_uid();
  384.         $node->polled = $node->polled ? ($node->polled .' '. $id) : $id;
  385.         db_query("UPDATE {poll} SET polled = '%s' WHERE nid = %d", $node->polled, $node->nid);
  386.         db_query("UPDATE {poll_choices} SET chvotes = chvotes + 1 WHERE nid = %d AND chorder = %d", $node->nid, $choice);
  387.         $node->allowvotes = false;
  388.         $node->choice[$choice]['chvotes']++;
  389.         drupal_set_message(t('Your vote was recorded.'));
  390.       }
  391.       else {
  392.         drupal_set_message(t("You're not allowed to vote on this poll."), 'error');
  393.       }
  394.     }
  395.     else {
  396.       drupal_set_message(t("You didn't specify a valid poll choice."), 'error');
  397.     }
  398.  
  399.     drupal_goto('node/'. $nid);
  400.   }
  401.   else {
  402.     drupal_not_found();
  403.   }
  404. }
  405.  
  406. /**
  407.  * Implementation of hook_view().
  408.  *
  409.  * @param $block
  410.  *   An extra parameter that adapts the hook to display a block-ready
  411.  *   rendering of the poll.
  412.  */
  413. function poll_view(&$node, $teaser = FALSE, $page = FALSE, $block = FALSE) {
  414.   global $user;
  415.   $output = '';
  416.  
  417.   if ($node->allowvotes && ($block || arg(2) != 'results')) {
  418.     $output .= poll_view_voting($node, $teaser, $page, $block);
  419.   }
  420.   else {
  421.     $output .= poll_view_results($node, $teaser, $page, $block);
  422.   }
  423.  
  424.   // Special display for side-block
  425.   if ($block) {
  426.     // No 'read more' link
  427.     $node->body = $node->teaser = '';
  428.  
  429.     $links = module_invoke_all('link', 'node', $node, 1);
  430.     $links[] = l(t('older polls'), 'poll', array('title' => t('View the list of polls on this site.')));
  431.     if ($node->allowvotes && $block) {
  432.       $links[] = l(t('results'), 'node/'. $node->nid .'/results', array('title' => t('View the current poll results.')));
  433.     }
  434.  
  435.     $output .= '<div class="links">'. theme("links", $links) .'</div>';
  436.   }
  437.  
  438.   $node->body = $node->teaser = $output;
  439. }
  440.  
  441. /**
  442.  * Implementation of hook_update().
  443.  */
  444. function poll_update($node) {
  445.   db_query('UPDATE {poll} SET runtime = %d, active = %d WHERE nid = %d', $node->runtime, $node->active, $node->nid);
  446.  
  447.   db_query('DELETE FROM {poll_choices} WHERE nid = %d', $node->nid);
  448.   foreach ($node->choice as $choice) {
  449.     $chvotes = (int)$choice['chvotes'];
  450.     $chtext = $choice['chtext'];
  451.  
  452.     if ($chtext != '') {
  453.       db_query("INSERT INTO {poll_choices} (nid, chtext, chvotes, chorder) VALUES (%d, '%s', %d, %d)", $node->nid, $chtext, $chvotes, $i++);
  454.     }
  455.   }
  456. }
  457.  
  458. ?>
  459.